
// pages/applyForService/applyForService.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    steps: [
      {
        text: '提交申请',
        i: 1
      },
      {
        text: '商家审核',
        i: 2
      },
      {
        text: '填写物流',
        i: 3
      },
      {
        text: '商家退款',
        i: 4
      },
      {
        text: '退款完成',
        i: 5
      }
    ],
    step: 3,
    address: '',
    userInfo: null,
    user_id: '',
    id: '',
    orderInfo: null,
    order_reason: null,
    dec: null,
    type: '',
    isCancel: false,
    pageFlag: true,
    address: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const info = wx.getStorageSync('uinfo')
    this.setData({
      userInfo: info,
      user_id: info.user.id,
      id: options.id
    })
    // let now = new Date().getTime()
    // console.log(`%c✅now=> `, 'color:#ff7b54;font-size:16px;', now)
  },
  dateFormat (dataString) {
    //dataString是整数，否则要parseInt转换
    var time = new Date(dataString)
    var year = time.getFullYear()
    var month = time.getMonth() + 1
    var day = time.getDate()
    var hour = time.getHours()
    var minute = time.getMinutes()
    var second = time.getSeconds()
    return year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
    return (day) + '天' + (hour) + '小时'
  },
  diffTime (startTime, endTime) {
    let runTime = parseInt((endTime - startTime) / 1000)
    let year = Math.floor(runTime / 86400 / 365)
    runTime = runTime % (86400 * 365)
    let month = Math.floor(runTime / 86400 / 30)
    runTime = runTime % (86400 * 30)
    let day = Math.floor(runTime / 86400)
    runTime = runTime % 86400
    let hour = Math.floor(runTime / 3600)
    runTime = runTime % 3600
    let minute = Math.floor(runTime / 60)
    runTime = runTime % 60
    let second = runTime
    let result = {
      year,
      month,
      day,
      hour,
      minute,
      second
    }
    // console.log(`相差${year}年${month}月${day}天${hour}小时${minute}分${second}秒`)
    return day + '天' + hour + '小时'
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showLoading()
    this.getOrderInfo()
    setTimeout(() => {
      wx.hideLoading()
    }, 300)
  },
  getOrderInfo () {
    wx.$api.orderReturn({ id: this.data.id, user_id: this.data.user_id }).then(res => {
      if (res.code && res.data) {
        let { status, type, checktime, admin_address, order_express, remark, is_receive } = res.data
        res.data.statusTxt = this.orderStatus(status + '')
        res.data.isShowCancel = [-1, 0, 1, 2, 6].includes(status)
        res.data.isShowKd = status == 1
        let step = this.stepStatus(status)
        // checktime = 1646320068097
        res.data.isShowAddr = [2, 3].includes(step)
        let dec = this.orderDec(step, type)
        if (step == 2 && checktime) {
          checktime = checktime * 1000
          let sevenDay = checktime + 86400000 * 7
          //大于10分钟
          let now = (new Date()).getTime()
          if ((sevenDay - now) > 600000) {
            dec.time = this.diffTime(now, sevenDay)
          } else {
            res.data.isShowKd = false
            dec.one = `您的订单已超时未上${type == 2 ? '换货' : '退货'}传物流信息，请与商家联系！`
            dec.time = null
            dec.two = null
          }
        }
        let address = ''
        if (admin_address) {
          address += admin_address.name + ' ' + admin_address.phone + '\r\n' + admin_address.address
        }
        if (status == 2) {
          dec.one = '等待商家退款...'
        }
        if (status == 4 && order_express) {
          let { express_name, express_no, create_time } = order_express
          dec.time = '\r\n'
          dec.two = `${this.dateFormat(create_time * 1000)}    ${express_name}    ${express_no}`
        }
        //售后申请被驳回
        if (status == -1 && remark) {
          dec = {}
          dec.time = '驳回原因：'
          dec.two = remark
        }
        //换货卖家已确认收货
        if (is_receive == 1 && status == 6) {
          dec.one = '商家已收货，等待商家发货...'
          res.data.statusTxt = '等待商家发货'
          res.data.isShowAddr = false
        }
        this.setData({
          orderInfo: res.data,
          order_reason: res.data.order_reason,
          step,
          dec,
          type,
          address
        })
        if (type == 2) {
          this.setData({
            'steps[4].text': '换货完成',
            'steps[3].text': '商家发货'
          })
        }
      } else {
        wx.showToast({
          title: '数据异常',
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              app.backPage()
            }, 1000)
          }
        })
      }
    })
  },
  orderStatus (val) {
    let type = {
      "-2": "订单关闭",
      "-1": "审核驳回",
      "0": "待审核",
      "1": "待退货",
      "2": "待退款",
      "3": "退款完成",
      "4": "换货待收货",
      "5": "换货已完成",
      "6": "待商家收货"
    }
    return type[val] ? type[val] : ''
  },
  orderDec (step, type) {
    if (step == 1) return { one: '等待商家审核...' }
    if (step == 2) {
      return {
        one: `商家已同意${type == 2 ? '换货' : '退货'}，请将商品退回到指定的地址，并在`,
        time: '6天22小时',
        two: '内填写物流信息'
      }
    }
    if (step == 3) return { one: type == 2 ? `物流单号已上传，等待商家收货...` : '物流单号已上传，等待商家收货...' }
    if (step == 4) return { one: type == 2 ? '商家已发货，请注意查收！' : '商家已退款，请注意查收！' }
  },
  stepStatus (val) {
    if (val < 0) {
      return 0
    }
    return val < 0 ? 0 : val == 0 ? 1 : val == 1 ? 2 : val == 2 ? 3 : val == 3 ? 5 : val == 4 ? 4 : val == 5 ? 5 : val == 6 ? 3 : 0
  },
  // 重新申请
  reApply () {
    wx.navigateTo({ url: `/pages/applyAfterInfo/applyAfterInfo?id=${this.data.id}&orderInfo=${JSON.stringify(this.data.orderInfo)}&type=${this.data.orderInfo.type}` })
  },
  cancel () {
    let { type } = this.data
    wx.showModal({
      content: '取消本次售后申请吗？',
      cancelText: '我再想想',
      confirmText: `取消${type == 2 ? '退货' : '退款'}`,
      success: (res) => {
        if (res.confirm) {
          // 按确定按钮
          this.orderReturnCancel()
        }
      }
    })
  },
  async orderReturnCancel () {
    let { code } = await wx.$api.orderReturnCancel({ user_id: this.data.user_id, id: this.data.id })
    if (code) {
      this.setData({ isCancel: true })
      wx.showToast({
        title: '取消成功！',
        success: () => {
          setTimeout(() => {
            app.backPage()
          }, 500)
        }
      })
    }
  },
  goOrderNo () {
    wx.navigateTo({ url: '/pages/orderNo/orderNo?id=' + this.data.orderInfo.id })
  },
  confirm () {
    wx.showModal({
      title: '确认已收到货',
      content: '为了保障售后权益，请检查后再确认收货',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#277CE3',
      success: (res) => {
        if (res.confirm) {
          wx.$api.returnConfirm({ id: this.data.orderInfo.id }).then(res => {
            if (!res.code) {
              wx.showToast({
                title: '确认收货成功！',
                icon: 'none',
                success: () => {
                  setTimeout(() => {
                    this.onShow()
                  }, 1000)
                }
              })
            }
          })
        }
      }
    })
  },
  setClipboardData () {
    wx.setClipboardData({
      data: this.data.address
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // if (!this.data.isCancel) {
    //   let page = getCurrentPages()
    //   if (page[page.length - 2].route == "pages/afterSale/afterSale") {
    //     wx.navigateBack()
    //   } else {
    //     let prevPage = pages[pages.length - 2]//上一页面
    //     prevPage.setData({
    //       //直接给上移页面赋值
    //       pageFlag: false
    //     })
    //     // this.setData({ pageFlag: false })
    //     wx.redirectTo({
    //       url: '/pages/afterSale/afterSale?flag=' + 1
    //     })
    //   }
    // }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

})